package com.webc.framework.bean;

import com.webc.framework.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;

/**
 * @author hejianglong
 * @date 2018/9/6.
 */
public class IocManager {

    private static final Map<String, Object> beanContainer = BeanContainer.getBeanContainer();

    static {
        initIoc();
    }

    public static void initIoc() {
        beanContainer.entrySet().forEach(entry -> {
            Object instance = entry.getValue();
            Field[] fields = instance.getClass().getDeclaredFields();
            Arrays.asList(fields).forEach(field -> {
                if(field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    try {
                        Object target = BeanContainer.getBean(field.getType().getName());
                        field.set(instance, target);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        });
    }
}
